#!/bin/bash
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

set -e  # Exit immediately when one of the commands fails.

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
EXAMPLES_DIR="$(realpath "${SCRIPT_DIR}/../examples")"

WORKSPACE_EXT=".xcworkspace"

# Keep a list of blacklisted iOS apps directories which should be excluded from
# the builds.
SKIPPED_BUILDS="
gesture_classification/ios
"

function build_ios_example {
  # Check if this directory appears in the skipped builds list.
  RELATIVE_DIR="${1#"${EXAMPLES_DIR}/"}"
  if echo "${SKIPPED_BUILDS}" | grep -qx "${RELATIVE_DIR}"; then
    echo "WARNING: Skipping build for ${RELATIVE_DIR}."
    return 0
  fi

  echo "=== BUILD STARTED: ${RELATIVE_DIR} ==="

  pushd "$1" > /dev/null

  # Cleanly install the dependencies
  pod install --repo-update --clean-install

  # Extract the workspace and target names.
  WORKSPACE_NAME="$(find * -type d -name "*${WORKSPACE_EXT}")"
  TARGET_NAME="$(basename "${WORKSPACE_NAME}" "${WORKSPACE_EXT}")"

  # Build the main scheme without code signing.
  xcodebuild \
      CODE_SIGN_IDENTITY="" \
      CODE_SIGNING_REQUIRED="NO" \
      CODE_SIGN_ENTITLEMENTS="" \
      CODE_SIGNING_ALLOWED="NO" \
      ARCHS="arm64" \
      -scheme "${TARGET_NAME}" \
      -workspace "${WORKSPACE_NAME}"

  popd > /dev/null

  echo "=== BUILD FINISHED: ${RELATIVE_DIR} ==="
  echo
  echo
}

build_ios_example "$1"
